// Background script for the extension
// Handles communication between popup and content scripts

// Listen for messages from content script or popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Forward messages from content script to popup
  if (sender.tab && message.from === 'content') {
    chrome.runtime.sendMessage({
      ...message,
      from: 'background'
    })
    return
  }
  
  // Forward messages from popup to content script
  if (message.from === 'popup' && message.to === 'content') {
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          ...message,
          from: 'background'
        })
      }
    })
    return
  }
  
  // Handle specific background actions
  if (message.action === 'getConfig') {
    chrome.storage.sync.get(['appConfig', 'modelConfig'], result => {
      sendResponse(result)
    })
    return true // Keep the message channel open for async response
  }
  
  // Handle config requests from content script
  if (message.action === 'requestConfig') {
    chrome.storage.sync.get(['appConfig', 'modelConfig'], result => {
      if (result.appConfig && result.modelConfig) {
        // Forward config to content script
        chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
          if (tabs[0]) {
            chrome.tabs.sendMessage(tabs[0].id, {
              action: 'updateConfig',
              data: {
                appConfig: result.appConfig,
                modelConfig: result.modelConfig
              }
            })
          }
        })
      }
    })
    return true
  }
})

// Log when extension is installed or updated
chrome.runtime.onInstalled.addListener(details => {
  console.log('Extension installed or updated:', details.reason)
}) 